/**
 * create by Alec
 */

import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import autobind from "autobind-decorator";
import { browserHistory } from 'react-router'
// import { Tabs } from '@ali/ding-ui';
// import { Tabs } from 'antd-mobile';


// components
import CardHeader from "../../components/CardHeader/index";
import DateRange from "../../components/DateRange2";
import ContrastChart from "../../components/contrastChart";
import ContrastChartDouble from "../../components/contrastChartDouble";

// submodule
import "./index.less";

// modules
import Breadcrumb from "./breadcrumb";
import TabPane from "./tabPane";
import DeptContrast from "./deptContrast";

// utils
import monitor from "../../utils/monitor.js";
import { get } from "../../utils/db.js";

import {
    setTitle,
    openLink,
    toast,
    setRight
} from "../../utils/dingtalk.js";

// actions
import { fetchWeeklyReportDetail } from "../../actions/weekly"

// 将store注入组件的props
const mapStateToProps = state => ({});
// 将action与dispatch进行绑定并注入组件的props
const mapDispatchToProps = dispatch => ({
    //区分绑定到props的action与传递的props
    actions: bindActionCreators(
        {
            dispatch,
            fetchWeeklyReportDetail
        },
        dispatch
    )
});

@connect(mapStateToProps, mapDispatchToProps)
export default class Weekly extends Component {
    static defaultProps = {
    };
    //propTypes 验证
    static propTypes = {
        actions: PropTypes.shape({
            dispatch: PropTypes.func.isRequired,
            fetchWeeklyReportQuery: PropTypes.func.isRequire,
            fetchWeeklyReportDetail: PropTypes.func.isRequire
        }).isRequired
    };
    constructor(props) {
        super(props);
        this.state = {
            weeklyData: {},
            reportQuery: {},
            breadList: [],
            active: 'entry',
            isLoading: false,
            showTransfer: true,
        };
        setRight({ show : false })
    }

    componentWillMount() {
        const corpId = get("corpId") || '';
        const { deptId = '', periodType = '', time = '' } = this.props.location.query || {};
        const params = { corpId, deptId, periodType, time };
        if (periodType === 'month') {
            setTitle({
                title: "月统计"
            });
        } else {
            setTitle({
                title: "周统计"
            });
        }
        this.getWeeklyReportDetail(params);
    }

    componentDidMount() {
        // window.addEventListener('popstate', this.getHistoryState)
    }

    componentWillUnmount() {
        // window.removeEventListener('popstate', this.getHistoryState)
    }
    componentWillUpdate() {
        const { periodType } = this.props.location.query || {};
        if (periodType === 'month') {
            setTitle({
                title: "月统计"
            });
        } else {
            setTitle({
                title: "周统计"
            });
        }

    }
    @autobind
    getHistoryState() {
        const corpId = get("corpId") || '';
        const { deptId = '', periodType = '', time = '' } = this.props.location.query || {};
        let params = {};
        if (window.history.state) {
            params = window.history.state;
        } else {
            params = { corpId, deptId, periodType, time }
        }
        this.getWeeklyReportDetail(params);
    }
    /**
     * 
     * @param {*corpId 企业ID*, deptId 部门ID, periodType week周 || month月, time周或月（yyyyMMdd）  } params 
     */
    @autobind
    // @monitor({})
    getWeeklyReportDetail(params) {
        if ([undefined, null, 'undefined', 'null'].some(val => val === params.time)) {
            params.time = '';
        }
        this.props.actions.fetchWeeklyReportDetail(params)
            .then(res => {
                const { success, result } = res;
                const nav = [{ deptName: "全部", deptId: "all" }];
                const { parentDeptList, currentMonth, currentWeek } = result;
                const deptList = parentDeptList || [];
                if (success) {
                    this.setState({
                        isLoading: true,
                        weeklyData: result,
                        showTransfer: result.showTransfer,
                        breadList: nav.concat(deptList),
                        currentDate: params.periodType === 'month' ? currentMonth.value : currentWeek.value,
                    })
                } else {
                    console.log('数据请求失败！')
                }
            })
            .catch(err => {
                console.log(err)
            })
    }

    /**
     * 日期切换 左侧回调
     */
    @autobind
    preDateCallback(lastTime) {
        window._rlog(`_weekly_preDate`);
        if (!lastTime) {
            toast({
                text: "没有数据"
            });
        } else {
            const corpId = get("corpId") || '';
            const { deptId = '', periodType = '' } = this.props.location.query || {};
            let params = {};
            // if (window.history.state) {
            //     params = window.history.state;
            //     params.time = lastTime;
            // } else {
            params = { corpId, deptId, periodType, time: lastTime }
            // }
            this.getWeeklyReportDetail(params);
        }
    }
    /**
     * 日期切换 右侧回调
     */
    @autobind
    nextDateCallback(nextTime) {
        window._rlog(`_weekly_nextDate`);
        if (!nextTime) {
            toast({
                text: "不能查看未来的数据"
            });
        } else {
            const corpId = get("corpId") || '';
            const { deptId = '', periodType = '' } = this.props.location.query || {};
            let params = {};
            // if (window.history.state) {
            //     params = window.history.state;
            //     params.time = nextTime;
            // } else {
            params = { corpId, deptId, periodType, time: nextTime }
            // }
            this.getWeeklyReportDetail(params);
        }
    }
    // tabs切换
    @autobind
    toggleActive(type) {
        this.setState({ active: type });
    }
    /**
    * 选择部门
    * @param {*所选部门} dept 
    */
    @autobind
    chooseDept(deptId) {
        const { periodType } = this.props.location.query || {};
        const { currentDate } = this.state;
        const corpId = get("corpId") || '';
       
        // const params = {
        //     time: currentDate,
        //     deptId: deptId,
        //     periodType: periodType,
        //     corpId
        // }
        // window.history.pushState(
        //     params,
        //     "",
        //     `#/personnelWeekly?deptId=${deptId}&time=${currentDate}&periodType=${periodType}`
        // );
        // this.getWeeklyReportDetail(params);
        // this.refs.weekly.scrollIntoView(true);
        openLink(`#/personnelWeekly?time=${currentDate}&deptId=${deptId}&periodType=${periodType}`);
    }

    /**
     * 面包屑菜单栏根据所选部门调取接口
     * @param {*部门ID} deptId 
     */
    @autobind
    handleBreadcrumb(deptId, index) {
        const { periodType } = this.props.location.query || {};
        const corpId = get("corpId") || '';
        let { currentDate, breadList } = this.state;
        if (breadList.length > 1 && deptId === breadList.slice(-1)[0].deptId) {
            return;
        }
        // const params = {
        //     time: currentDate,
        //     periodType: periodType,
        //     corpId
        // }
        if (deptId === "all") {
            openLink(`#/personnelWeekly?time=${currentDate}&periodType=${periodType}`);
            // window.history.pushState(
            //     params,
            //     "",
            //     `#/personnelWeekly?time=${currentDate}&periodType=${periodType}`
            // );
        } else {
            openLink(`#/personnelWeekly?time=${currentDate}&deptId=${deptId}&periodType=${periodType}`);
            // window.history.pushState(
            //     params,
            //     "",
            //     `#/personnelWeekly?time=${currentDate}&deptId=${deptId}&periodType=${periodType}`
            // );
            // params.deptId = deptId
        }
        // this.getWeeklyReportDetail(params);
    }

    render() {
        const { weeklyData, breadList, active, isLoading, showTransfer } = this.state;
        const { periodType } = this.props.location.query || {};
        const dateRange = {
            currentMonth: weeklyData.currentMonth,
            lastMonth: weeklyData.lastMonth,
            nextMonth: weeklyData.nextMonth,
            currentWeek: weeklyData.currentWeek,
            lastWeek: weeklyData.lastWeek,
            nextWeek: weeklyData.nextWeek,
            periodType
        };
        const contrastData = {
            type: periodType === 'month' ? '月' : '周',
            totalEntry: weeklyData.totalEntry, //入职人数
            totalDismission: weeklyData.totalDismission, //离职人数
            startNum: weeklyData.startNum, //期初人数
            endNum: weeklyData.endNum, //期末人数
            transferIn: weeklyData.transferIn, //转入人数
            transferOut: weeklyData.transferOut, //转出人数
        };
        const breadcrumb = weeklyData.parentDeptList || [];
        const { deptCompare = [] } = weeklyData;
        return (
            <div className="weekly">
                {
                    isLoading ?
                        <div>
                            <div ref="weekly">
                                <DateRange dateRange={dateRange}
                                    onLeftClick={this.preDateCallback}
                                    onRightClick={this.nextDateCallback}
                                />
                            </div>

                            <div className="weekly-con">
                                {
                                    breadList.length > 1 &&
                                    <Breadcrumb breadcrumb={breadList}
                                        handleBreadcrumb={this.handleBreadcrumb}
                                    />
                                }

                                <div className="personnel-statistics">
                                    <CardHeader title={'人员统计'} />
                                    {
                                        showTransfer 
                                        ? <ContrastChartDouble data={contrastData} /> 
                                        : <ContrastChart data={contrastData} />
                                    }

                                </div>




                                <TabPane active={active}
                                    toggleActive={this.toggleActive}
                                    analysisData={weeklyData}
                                />

                                <DeptContrast deptCompare={deptCompare}
                                    chooseDept={this.chooseDept}
                                />

                            </div>
                        </div> : null
                }

            </div>
        );
    }
}